# app/concerns/stair_master/controller.rb
##
##
##
module StairMaster
  module Controller
    extend ActiveSupport::Concern

    include ::StairMaster::Concerns::Traversal
    include ::StairMaster::Concerns::Getters
    include ::StairMaster::Concerns::Ordering
    include ::StairMaster::Concerns::Tests
    include ::StairMaster::Concerns::Routing

    included do
      helper_method :workflow_map, :params_for_redirect
      before_filter :skip_step!, only: [:show, :update]

      class << self
        attr_reader :stair_master_workflow_map
      end
    end

    def workflow_map
      @workflow_map ||= (
        @stair_master_workflow_map ||= (
          self.class.ancestors.map do |a|
            a.stair_master_workflow_map if a.respond_to? :stair_master_workflow_map
          end.flatten.compact.first
        )

        map = @stair_master_workflow_map.present? ? @stair_master_workflow_map : self.class.workflow_map

        map.new
      )
    end

    private # ---------------------------------------------

    ## Override this method in your controller to set the params
    def params_for_redirect(*bad_keys)
      mod_params   = params
      default_keys = [:action, :controller, :authenticity_token, :utf8]
      (bad_keys + default_keys).each do |k|
        mod_params.delete k
      end

      mod_params.empty? ? nil : mod_params
    end

    def skip_step!
      redirect_to next_step_path(params_for_redirect) if step_should_be_skipped?
    end

    module ClassMethods
      def workflow_map(map_class=nil)
        return (@stair_master_workflow_map || ::StairMaster::WorkflowMap) if map_class.nil?
        @stair_master_workflow_map = map_class.to_s.camelize.constantize
      end
    end
  end
end
